package ch.rheintalconnection.sysventory.technicalServices.hibernate;

import javax.persistence.*;

import org.apache.log4j.Logger;

import ch.rheintalconnection.sysventory.domain.Scan;
import ch.rheintalconnection.sysventory.technicalServices.IDataWriter;

public class MySqlDataWriter implements IDataWriter {

	private static EntityManagerFactory emf = null;
	private static EntityManager em = null;
	private static EntityTransaction tx = null;

	private Logger logger;

	public MySqlDataWriter() {
		super();
		this.logger = Logger.getLogger(MySqlDataWriter.class);

		emf = Persistence
				.createEntityManagerFactory("ch.rheintalconnection.sysventory");
		em = emf.createEntityManager();

		tx = em.getTransaction();		
	}

	public void store(Scan scan) {
		try {
			tx.begin();
			em.persist(scan);
			em.flush();
			tx.commit();
			em.clear();
			
			logger.info("scan "+scan.getId()+" is stored in the database.");

		} catch (Exception e) {
			e.printStackTrace();
			tx.rollback();
		}
	}
}
